package bi

import android.content.Context
import yyee.llee.mmee.base_api_factory.ModuleConfig.AD_LOG_TAG
import java.io.*
import kotlin.experimental.xor

object fileUtils {

    fun copyAssetToFile(
        paramContext: Context,
        assetFileName: String,
        targetFile: File?,
        encrypt: Int = 0
    ): Boolean {
        var localInputStream: InputStream? = null
        var localFileOutputStream: FileOutputStream? = null
        try {
            localInputStream = paramContext.assets.open(assetFileName)
            localFileOutputStream = FileOutputStream(targetFile)
            copyStream(localInputStream, localFileOutputStream, encrypt)
            bi.GL.d(AD_LOG_TAG, "插件COPY 完成")
            return true
        } catch (e: Throwable) {
            bi.GL.d(AD_LOG_TAG, "插件COPY ERROR$e")
            e.printStackTrace()
        } finally {
            try {
                localInputStream?.close()
            } catch (e: Exception) {
            }
            try {
                localFileOutputStream?.close()
            } catch (e: Exception) {
            }
        }
        return false
    }


    @Throws(IOException::class)
    private fun copyStream(paramInputStream: InputStream, paramOutputStream: OutputStream, encrypt: Int = 0) {
        val arrayOfByte = ByteArray(4*1024)
        var i = 0
        while (paramInputStream.read(arrayOfByte).also { i = it } > 0) {
            when (encrypt) {
                0-> paramOutputStream.write(arrayOfByte, 0, i)
                1->{
                    val encryptByte = ByteArray(i)
                    for (temp in 0 until i) {
                        encryptByte[temp] = arrayOfByte[temp] xor  0x12
                    }
                    paramOutputStream.write(encryptByte)
                }
                2->{
                    val decryptByte = ByteArray(i)
                    for (temp in 0 until i) {
                        decryptByte[temp] = arrayOfByte[temp] xor  0x12
                    }
                    paramOutputStream.write(decryptByte)
                }
            }
        }
        paramOutputStream.flush()
    }
}